<?php

class CategoryService extends AbstractService
{

    protected function _init()
    {
	$this->setMapper(new CategoryMapper());
    }

    public function getByName($name)
    {
	if (!$name) {
	    return false;
	}
	$cacheSlot = new CacheSlotsCategoryList(array('name' => $name));
	if (($data = $cacheSlot->load()) === false) {
	    $data = $this->getMapper()->getBy("name = :name", array(":name" => $name));
	    $cacheSlot->setData($data)->save();
	}
	return $data;
    }

    public function getCategoryTree()
    {	
	$cacheSlot = new CacheSlotsCategoryList();
	if (($data = $cacheSlot->load()) === false) {	    
	    $data = $this->_getRelationTree($this->getMapper()->getAll());	    
	    $cacheSlot->setData($data)->save();
	}	
	return $data;
    }

    protected function _getRelationTree($models, $parentId = null)
    {
	if (!$models) {
	    return array();
	}
	$data = array();
	$allModels = $models;
	foreach ($models as $model) {
	    if ($model->parent_id == $parentId) {
		$model->setChildren($this->_getRelationTree($allModels, $model->getId()));
		$data[$model->getId()] = $model;
	    }
	}	
	return $data;
    }

}